package com.jt.resource.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 基于过滤器做跨域配置
 */
//@Configuration
public class CorsFilterConfig {
    //Spring MVC中注册过滤器使用FilterRegistrationBean对象
    @Bean
    public FilterRegistrationBean<CorsFilter>  filterRegistrationBean(){
        //1.构建基于Url方式的跨域配置对象
        UrlBasedCorsConfigurationSource configSource=
                new UrlBasedCorsConfigurationSource();
        //2.构建url请求规则配置
        CorsConfiguration config=new CorsConfiguration();
        //2.1允许所有请求头跨域
        config.addAllowedHeader("*");
        //2.2允许所有请求方式(get,post,put,...)
        config.addAllowedMethod("*");//get,post,
        //2.3允许所有请求ip,port跨域
        config.addAllowedOrigin("*");//http://ip:port
        //2.4允许携带cookie进行跨域
        config.setAllowCredentials(true);
        //2.5将这个跨域配置应用到具体的url
        configSource.registerCorsConfiguration("/**",config);
        //3.注册过滤器
        FilterRegistrationBean fBean=
                new FilterRegistrationBean(
                    new CorsFilter(configSource));
        //设置过滤器优先级
        fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return fBean;
    }
}
